package com.spark.trouble.handle

import android.annotation.SuppressLint
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.view.View
import com.blankj.utilcode.util.LogUtils
import com.google.gson.Gson
import com.spark.colliery.common.ext.gone
import com.spark.common.BaseFragment
import com.spark.common.Const
import com.spark.common.ext.*
import com.spark.common.helper.DatePickerDiaFragment
import com.spark.common.model.ResultModel
import com.spark.common.net.Http
import com.spark.common.net.toJsonBody
import com.spark.common.widget.RejectAlert
import com.spark.trouble.R
import com.spark.trouble.RectifyFragment
import com.spark.trouble.model.RespUnitModel
import com.spark.trouble.model.TroubleDealListModel
import kotlinx.android.synthetic.main.frag_limit_handle.*
import me.yokeyword.fragmentation.SupportFragment
import java.util.*

/**
 * 挂牌督办
 */
@SuppressLint("SetTextI18n")
class SupervisoryHandleFragment : BaseFragment() {
    private var prop: TroubleDealListModel.ResultMap? = null
    private val reqHTLevel = 0x1001
    private val reqUnit = 0x1002
    private var respUnitModel: RespUnitModel.ResultMap? = null
    private lateinit var participantsAdapter: ParticipantsAdapter
    private var participants: ParticipantModel = ParticipantModel()
    private var timer = Timer()
    private lateinit var tictoc: TimerTask
    private var serialNum = ""

    private var sourceType = 0
    private var taskType = "7"
    private var isUndispatchTask: Boolean = true

    companion object {
        fun newInstance(sourceType: Int, prop: String, taskType: String): SupervisoryHandleFragment {
            val target = SupervisoryHandleFragment()
            val args = Bundle()
            args.apply {
                putString("prop", prop)
                putInt("sourceType", sourceType)
                putString("taskType", taskType)
            }
            target.arguments = args
            return target
        }
    }

    override fun contentResId(): Int {
        return R.layout.frag_limit_handle
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        arguments?.apply {
            sourceType = getInt("sourceType")
            taskType = getString("taskType")

            getString("prop")?.apply {
                prop = Gson().fromJson(this, TroubleDealListModel.ResultMap::class.java)?.apply {
                    isUndispatchTask = taskType == "7"

                    when(sourceType){
                        Const.htTypeProcess -> {
                            when (state) {
                            // 审核中
                                "2" -> {
                                    ll_ctrl.gone(true)
                                    btn_submit.gone(true)
                                }
                            // 被驳回
                                "3" -> {
                                    ll_ctrl.gone(true)
                                    btn_submit.gone(true)
                                }
                            // 待归档
                                "4" -> {
                                    ll_ctrl.gone(false)
                                    btn_submit.gone(true)
                                    tv_draft.setOnClickListener { toSave(task_id.toString(), "1") }
                                    btn_submit_.setOnClickListener { toSave(task_id.toString(), "2") }
                                }
                            }
                            fetchInfo(task_id.toString())
                        }
                        Const.htTypeAgency -> {
                            when (state) {
                            // 待审核
                                "2" -> {
                                    ll_ctrl.gone(false)
                                    btn_submit.gone(true)
                                    tv_draft.apply {
                                        text = "驳回"
                                        setOnClickListener {
                                            activity?.apply {
                                                RejectAlert.Builder(this, "驳回理由", "请输入驳回理由")
                                                        .affirm { d, str ->
                                                            if (str.isNullOrBlank()) {
                                                                alert("请输入驳回理由")
                                                            } else {
                                                                d.dismiss()
                                                                // submitAgencyRejectVerifyConfirm(task_id.toString(), str!!)
                                                            }
                                                        }
                                                        .cancel { d, i ->
                                                            d.dismiss()
                                                        }
                                                        .create()
                                                        .show()
                                            }
                                        }
                                    }
                                    btn_submit.apply {
                                        text = "通过"
                                        setOnClickListener {
                                            // submitAgencyToVerifyConfirm(task_id.toString(), approveState = "2")
                                        }
                                    }
                                    // fetchAgencyToVerifyConfirm("$task_id")
                                }
                            // 待确认
                                "4" -> {
                                    ll_ctrl.gone(false)
                                    btn_submit.gone(true)
                                    tv_draft.apply {
                                        text = "驳回"
                                        setOnClickListener {
                                            activity?.apply {
                                                RejectAlert.Builder(this, "驳回理由", "请输入驳回理由")
                                                        .affirm { d, str ->
                                                            if (str.isNullOrBlank()) {
                                                                alert("请输入驳回理由")
                                                            } else {
                                                                d.dismiss()
                                                                // submitAgencyRejectVerifyConfirm(task_id.toString(), str!!)
                                                            }
                                                        }
                                                        .cancel { d, i ->
                                                            d.dismiss()
                                                        }
                                                        .create()
                                                        .show()
                                            }
                                        }
                                    }
                                    btn_submit.apply {
                                        text = "通过"
                                        setOnClickListener {
                                           // submitAgencyToVerifyConfirm(task_id.toString(), confirmState = "4")
                                        }
                                    }
                                    // fetchAgencyToVerifyConfirm("$task_id")
                                }
                            // 待整改
                                "5" -> {
                                    ll_ctrl.gone(true)
                                    btn_submit.apply {
                                        text = "进行整改"
                                        setOnClickListener {
                                            // submitAgencyToRectify("$task_id")
                                            parentFragment?.let { it as SupportFragment }?.start(RectifyFragment.newInstance("$task_id"))
                                        }
                                    }
                                   // fetchAgencyRehandleVerify("$task_id")
                                }
                            // 整改中 todo 状态和待整改一致
                                "x" -> {
                                    ll_ctrl.gone(false)
                                    btn_submit.gone(true)

                                    tv_draft.apply {
                                        text = "暂存"
                                        setOnClickListener {

                                        }
                                    }
                                    btn_submit_.apply {
                                        text = "整改完成"
                                        setOnClickListener {

                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        serialNum = Const.genSerialNum()
        // 序列号
        tv_serial_num.text = "编号: $serialNum"
        // 责任单位
        tv_resp_unit.setOnClickListener {
            parentFragment?.let { it as SupportFragment }?.startForResult(ChooseChoiceFragment.newInstance(ChooseChoiceFragment.unit), reqUnit)
        }
        // 隐患等级
        tv_ht_level.setOnClickListener {
            parentFragment?.let { it as SupportFragment }?.startForResult(ChooseChoiceFragment.newInstance(ChooseChoiceFragment.htLevel), reqHTLevel)
        }
        // 时限
        et_time_limit.setOnClickListener {
            val datePicker = DatePickerDiaFragment.newInstance()
            datePicker.show(childFragmentManager, "DatePicker")
            datePicker.setOnDateTapedListener {
                et_time_limit.text = sdf().format(it)
            }
        }
        // 参与人员
        participantsAdapter = ParticipantsAdapter(R.layout.item_participant)
        recy_joins.apply {
            layoutManager = object : GridLayoutManager(context, 4) {
                override fun canScrollHorizontally(): Boolean {
                    return false
                }

                override fun canScrollVertically(): Boolean {
                    return false
                }
            }
            adapter = participantsAdapter
        }
        // 由于
        tv_ht_desc.text = prop?.source_description
        // 扣分
        et_lost_point.apply {
            trackPostfix("分")
            setText("${prop?.source_score}分")
        }
        // 罚金
        et_fine.apply {
            trackPostfix("元")
            setText("${prop?.source_money}元")
        }
        // 时间
        tv_limit_time
        // 制作人
        tv_author.text = Const.getUser()?.user?.name
        // 提交
        btn_submit.setOnClickListener {
            submitCheck()
        }
    }

    override fun onSupportVisible() {
        super.onSupportVisible()
        startTictoc()
    }

    override fun onSupportInvisible() {
        super.onSupportInvisible()
        stopTictock()
    }

    private fun startTictoc() {
        if (isUndispatchTask) {
            tictoc = object : TimerTask() {
                override fun run() {
                    val time = sdf("MM月dd日 mm:ss").format(System.currentTimeMillis())
                    activity?.runOnUiThread {
                        tv_limit_time.text = time
                    }
                }
            }
            timer.schedule(tictoc, 0, 1000)
        }
    }

    private fun stopTictock() {
        if (isUndispatchTask) {
            if (!tictoc.cancel()) {
                tictoc.cancel()
            }
        }
    }

    override fun onFragmentResult(requestCode: Int, resultCode: Int, data: Bundle?) {
        when (requestCode) {
            reqHTLevel -> {
                if (resultCode == ChooseChoiceFragment.resHTLevel) {
                    data?.apply {
                        val level = getString("level")
                        LogUtils.e("【Level】$level")
                        tv_ht_level.text = level
                    }
                }
            }
            reqUnit -> {
                if (resultCode == ChooseChoiceFragment.resUnit) {
                    data?.apply {
                        Gson().fromJson(getString("unit"), RespUnitModel.ResultMap::class.java)?.apply {
                            tv_resp_unit.text = this.name
                            respUnitModel = this
                            participants.members.apply {
                                add(ParticipantModel.Member(respUnitModel!!.acceptanceInfo.name, "", "验收"))
                                add(ParticipantModel.Member(respUnitModel!!.leaderInfo.name, "", "责任"))
                                add(ParticipantModel.Member(respUnitModel!!.technicianInfo.name, "", "技术"))
                            }
                            participantsAdapter.addData(participants.members)
                        }
                    }
                }
            }
        }
    }

    @SuppressLint("CheckResult")
    private fun submitCheck() {
        // responsible unit
        val respUnit = tv_resp_unit.text.toString().trim()
        if (respUnit.isNullOrBlank()) {
            alert("请输入责任单位")
            return
        }
        // ht-level
        val htLevel = tv_ht_level.text.toString().trim()
        if (htLevel.isNullOrBlank()) {
            alert("请输入隐患等级")
            return
        }
        // time limit
        val timelimit = et_time_limit.text.toString().trim()
        if (timelimit.isNullOrBlank()) {
            alert("请输入时限")
            return
        }
        // participants
        if (participantsAdapter.data.isEmpty()) {
            alert("请输入参与人员")
            // return
        }
        // cause
        val htDesc = tv_ht_desc.text.toString().trim()
        if (htDesc.isNullOrBlank()) {
            alert("请输入隐患缘由")
            return
        }
        // lost-point
        val lostPoint = et_lost_point.string()
        if (lostPoint.isNullOrBlank()) {
            alert("请输入扣分")
            return
        }
        // fine
        val fine = et_fine.string()
        if (fine.isNullOrBlank()) {
            alert("请输入罚金")
            return
        }
        // goal
        val goal = et_goal.string()
        if (goal.isNullOrBlank()) {
            alert("请输入整改目标")
            return
        }
        val params = mutableMapOf(
                Pair("taskId", prop?.task_id ?: ""),
                Pair("troubleLevel", htLevel),
                Pair("troubleDepartmentId", respUnitModel?.department_id ?: ""),
                Pair("responsibleScore", lostPoint.substring(0, lostPoint.length - 1)),
                Pair("responsibleMoney", fine.substring(0, fine.length - 1)),
                Pair("noticeNo", serialNum),
                Pair("troubleType", "2"),
                Pair("solutionType", "1"),
                Pair("solutionGoal", goal),
                Pair("processorId", respUnitModel?.processor_id ?: ""),
                Pair("technicianId", respUnitModel?.technician_id ?: ""),
                Pair("acceptanceId", respUnitModel?.acceptance_id ?: ""),
                Pair("leaderId", respUnitModel?.leader_id ?: ""),
                Pair("sulotionTime", sdf().format(System.currentTimeMillis())),
                Pair("limitTime", et_time_limit.text.toString().trim())
        )
        Http.request()
                .rxPost("${Const.base_url}${Const.act_limit_supervisor}", params.toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, HandleSubmitResultModel::class.java)?.apply {
                                if (code == "200") {
                                    success("提交成功")
                                } else {
                                    error("提交失败")
                                }
                                activity?.finish()
                            }
                        },
                        {
                            it.printStackTrace()
                            hideLoader()
                            report(it)
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading("提交中...")
                        }
                )

    }

    @SuppressLint("CheckResult")
    private fun fetchInfo(taskId: String) {
        val params = mutableMapOf("taskId" to taskId)
        Http.request()
                .rxPost("${Const.base_url}${Const.act_chk_be_reject}", params.toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, LimitHandleInfoModel::class.java)?.apply {
                                if (code == "200") {
                                    restore(this)
                                }
                            }
                        },
                        {},
                        {},
                        {}
                )
    }

    @SuppressLint("SetTextI18n")
    private fun restore(data: LimitHandleInfoModel) {
        if (data.resultMaps.isNotEmpty()) {
            data.resultMaps[0].apply {
                tv_resp_unit.text = departmentName
                tv_ht_level.text = trouble_level
                et_time_limit.text = "$rectify_day"
                tv_ht_desc.text = trouble_content
                et_lost_point.setText("${responsible_score}分")
                et_fine.setText("${responsible_money}元")
                et_goal.setText(solution_goal)

                participants.members.apply {
                    add(ParticipantModel.Member(name = leaderName, position = "责任"))
                    add(ParticipantModel.Member(name = acceptor_name, position = "验收"))
                    add(ParticipantModel.Member(name = technician_name, position = "技术"))
                }
                participantsAdapter.addData(participants.members)
            }
        }
    }

    /**
     * 待存储
     * @param state 1 => 存储 2 => 归档
     */
    @SuppressLint("CheckResult")
    private fun toSave(taskId: String, state: String) {
        val params = mutableMapOf(
                Pair("taskId", taskId),
                Pair("saveType", state)
        )
        Http.request()
                .rxPost("${Const.base_url}${Const.act_limit_supervisory_to_save}", params.toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, ResultModel::class.java)?.apply {
                                if (code == "200") {
                                    toast("提交成功")
                                    pop()
                                } else {
                                    toast("失败")
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading("提交中...")
                        }
                )
    }

    @SuppressLint("CheckResult")
    private fun fetch() {
        Http.request()
                .rxPost("${Const.base_url}${Const.act_supervisor_fetch}", "{}".toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            LogUtils.e(it)
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading()
                        }
                )

    }
}